import request from "@/utils/request";

import Cookies from "js-cookie";
import CryptoJS from 'crypto-js'
import {
  generateUUID,ak
} from "@/utils/ruoyi";
// 上传到七牛云相关
export function getQiniuKey(model, filename) {
  const uuid = generateUUID()
  const year = new Date().getFullYear()
  const month = new Date().getMonth() + 1
  const day = new Date().getDate()
  const houzhui = filename ? filename.split('.')[filename.split('.').length - 1] : 'jpg'
  const key = `${model}/${year}${month}${day}/${uuid}.${houzhui}`
  return key

}
// 解密
export function decryptNoiv(encryptedContent) {
	if (!encryptedContent) {
		console.error("[AESUtil.decrypt] content is empty");
		return null;
	}

	try {
		// 将十六进制字符串转换为字节数组
		let encryptedBytes = CryptoJS.enc.Hex.parse(encryptedContent);
		// 将字节数组转换为Base64字符串
		let base64Encrypted = CryptoJS.enc.Base64.stringify(encryptedBytes);
		// 使用AES ECB模式解密
		let decrypted = CryptoJS.AES.decrypt(base64Encrypted, CryptoJS.enc.Utf8.parse(ak), {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		// 将解密后的数据转换为UTF-8字符串
		return decrypted.toString(CryptoJS.enc.Utf8);
	} catch (e) {
		console.error("AESUtil.decrypt fail, error:", e.message);
		return null;
	}
}
// 获取七牛云鉴权参数
export function getQiniuToken(tenantId) {
  return new Promise((resolve, reject) => {
    const upTokenStr = Cookies.get('upTokenObj'+tenantId)
    const now = new Date().getTime().toString()
    if(upTokenStr){
      const upTokenObj = JSON.parse(upTokenStr)
      if (upTokenObj && upTokenObj.expireTime > now) {
        return resolve(upTokenObj)
      }
    }
    
    request({
      url: `/upload/getPeiZhi`,
      method: 'post',
      data:{}
    }).then(res => {
      if (res.code == 200) {
        const objStr = decryptNoiv(res.data)
        if (objStr) {
          const obj = JSON.parse(objStr)
          Cookies.set('upTokenObj'+tenantId, objStr)
          resolve(obj)
        }
      }
    }).catch(err => {
      reject(err.msg)
    })
  })
}
// 文件上传方法
export function uploadFileFn(file,tenantId,model='goods/pc',type='jpg'){
  return new Promise(async (resolve, reject) => {
      const key = getQiniuKey(model,type)
      const tokenObj = await getQiniuToken(tenantId)
      const putExtra = {}
      const config = {}
      const observer = {
          next(res) {
              // console.log('上传过程', res)
          },
          error(err) {
              // ...
              console.log('上传失败', err)
              reject({
                  ...tokenObj,
                  err: err
              })
          },
          complete(res) {
              resolve({
                  ...tokenObj,
                  ...res
              })
          }
      }
      const observable = qiniu.upload(
          file,
          key,
          tokenObj.upToken,
          putExtra,
          config
      )
      observable.subscribe(observer) // 上传开始
  })
}


//检查文件是否已存在
export function api_FileCheck(fileCheckReq) {
  return request({
    url: "/uploadFile/check",
    method: "post",
    timeout: 600*1000,
    data: fileCheckReq
  });
}

//上传分片
export function api_UploadChunk(uploadChunkReq) {
  return request({
    url: "/uploadFile/chunk",
    method: "post",
    data: uploadChunkReq,
    timeout: 600*1000
  });
}
//合并文件
export function api_UploadFile(uploadFileReq) {
  return request({
    url: "/uploadFile/chunk/merge",
    method: "post",
    timeout: 600*1000,
    data: uploadFileReq
  });
}
// 文件上传
export function postUpload(file) {
  return request({
    url: "/upload/imageHead",
    method: "post",
    data: file,
    timeout: 600*1000,
  });
}
export function postUploadImage(file) {
  return request({
    url: "/upload/image",
    method: "post",
    data: file,
    timeout: 600*1000,
  });
}
// 创建临时缓存  扫码上传图片
export function creatrandomStr(data) {
  return request({
    url: "/goods/info/creat/randomStr",
    method: "post",
    data,
  });
}
// 清除缓存 并返回给前端
export function closerandomStr(data) {
  return request({
    url: "/goods/info/close/randomStr",
    method: "post",
    data,
  });
}
